<template>
	<basic-container>
		<avue-crud :option="option" :data="data" ref="crud" v-model="form" :table-loading="loading" :permission="permissionList"
		@row-save='addSave' @row-del="rowDel" @row-update="rowUpdate" :page="page"  @refresh-change="refreshChange"
		@search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange" @current-change="currentChange"
		@size-change="sizeChange" @on-load="onLoad">
			<template slot="search">
				<el-col style="margin-top: 0.7rem;width: 80px;">
					<span>地区：</span>
				</el-col>
				<el-col :span="5" style="margin-right: 1rem;margin-top: 0.4rem;">
					<el-select size="small" v-model="areaId" placeholder="省份" @change="changeArea">
						<el-option v-for="item in areas" :key="item.id" :label="item.area_name" :value="item.id">
						</el-option>
					</el-select>
				</el-col>
				<el-col :span="5" style="margin-right: 1rem; margin-top: 0.4rem;">
					<el-select size="small" v-model="cityId" placeholder="城市">
						<el-option v-for="item in citys" :key="item.id" :label="item.area_name" :value="item.id">
						</el-option>
					</el-select>
				</el-col>
			</template>
			<template slot="menuLeft">
				<el-button type="primary" size="mini" @click="deletAll()" v-has="'/mall-cloud-base/area/deleteAll'">批量删除</el-button>
			</template>
			<!-- 是否显示插槽 -->
			<template slot-scope="{row}" slot="common">
				<el-switch @change="rowSwitchChange(row)" v-model="row.common">
				</el-switch>
			</template>

			<template slot="parentIdType" slot-scope="{item,value,label}">
				<span>{{label}}</span>
			</template>


		</avue-crud>
	</basic-container>
</template>

<script>
	import {
		getList,
		remove,
		update,
		add,
		updateDisplay,
		removeAll,
		getAreaListByLevel,
        getListTree
	} from "@/api/admin/area";
	// import Vue from 'vue'
	import {zipCode} from '@/util/rej'
	import {
		mapGetters
	} from "vuex";
    import {
        testSort
    } from '@/util/util'
	export default {
		data() {
			var validateAreaName = (rule, value, callback) => {
				if (value === '') {
					callback('请输入地区名称')
				} else if (value.length < 3 || value.length > 8) {
					callback('地区名长度为3-8个字符')
				} else if (!(/^[\u4e00-\u9fa5]+$/).test(value)) {
					callback('地区名应为中文')
				} else {
					callback();
				}
			};
			return {
				form: {},
				query: {},
				loading: true,
				rolesTree: [],
				rolesKeys: [],
				box: false,
				areas: [],
				citys: [],
				page: {
					pageSize: 10,
					currentPage: 1,
					total: 0
				},
				areaId: null,
				cityId: null,
				idList: [],
				option: {
					size: 'mini',
					tip: false,
					border: true,
					index: true,
					selection: true,
					searchsolt: true,
					viewBtn: false,
					//addRowBtn: true,
					//cellBtn: true,
					editBtn: true,
					rowKey: 'id',
					height: 'auto',
					// calcHeight: 380,
					dialogType: 'dialog',
					menuWidth: 160,
					column: [{
							label: "地区名称",
							prop: "areaName",
							fixed: true,
							rules: [{
								required: true,
								validator: validateAreaName,
								trigger: "blur"
							}],
							cell: true,
						},
						{
							label: "邮政编码",
							prop: "zip",
							maxlength: 6,
							rules: [{
								required: true,
								validator: zipCode,
								trigger: "blur"
							}],
						},
						{
							label: "序号",
							prop: "sequence",
							type: 'input',
							sortable: false,
							rules: [{
								required: true,
								type: 'input',
								validator: testSort,
								trigger: "blur"
							}],
							cell: true
						},
                        {
                            lazy:true,
                            label:'父级地区',
                            prop: "parentId",
							props: {
								label: "label",
								value: "value",
								children: "children"
							},
                            type:'tree',
                            // dicUrl: "/base/area/getTreeSelect",
							dicData:[],
                            lazy:true,
							rules: [{
								required: true,
								message: '请选择省份',
								trigger: 'change'
							}],
                        },
						{
							label: '是否显示',
							prop: 'common',
							type: 'switch',
							slot: true,
							cell: true,
							displayAs: 'switch'
						}
					]
				},
				data: []
			};
		},
		created() {
			this.onLoad(this.page);
			//省级选择框
			getAreaListByLevel(null, 0).then(res => {
				this.areas = res.data.data;
			})
		},
		computed: {
			...mapGetters(["permission", 'userInfo']),
			permissionList() {
				return {
					addBtn: this.vaildData(this.permission["/mall-cloud-base/area/addItem"], false),
					addRowBtn: this.vaildData(this.permission["/mall-cloud-base/area/addItem"], false),
					viewBtn: this.vaildData(this.permission["/mall-cloud-base/area/detail"], false),
					delBtn: this.vaildData(this.permission["/mall-cloud-base/area/delete"], false),
					editBtn: this.vaildData(this.permission["/mall-cloud-base/area/editItem"], false),
					cellBtn: this.vaildData(this.permission["/mall-cloud-base/area/editItem"], false)
				};
			},
		},
		methods: {
			//选择地区
			changeArea() {
				//省级选择框
				getAreaListByLevel(this.areaId, 1).then(res => {
					this.cityId="";
					this.citys = res.data.data;
					console.log(this.citys)
				})
			},
			addSave(row,loading,done) {
				console.log(row)
				console.log(this.form)
				console.log("新增")
				add(row).then(res => {
					console.log(res)
				    if(res.data.success){
                        loading();
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                        done();
					}
					else{
                        done();
                    }

				});
			},
			rowUpdate(row, index, loading, done) {
				row.position = row.positionIds;
				update(row).then(res => {
				    if(res.data.success){
                        loading();
                        this.onLoad(this.page);
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                        done();
					}
					else{
                        done();
					}

				});
			},
			rowDel(row) {
				this.$confirm("确定将选择数据删除?", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning"
					})
					.then(() => {
						return remove(row.id).then(res => {
							if (res.data.success) {
								if (this.data.length == 1) {
									this.page.currentPage -= 1
								}
								this.onLoad(this.page);
								this.$message({
									type: "success",
									message: "操作成功!"
								});
							}
							else{
								this.$message.error(res.data.message);
							}
						})
						.catch(() => {
							this.$message({
								type: 'info',
								message: '已取消删除'
							})
						})

					})
			},
			//清空
			searchReset() {
				console.log("000")
				this.citys = [];
				this.idList = []
				this.$refs.crud.toggleSelection();
				this.query = {};
				this.query.parentId = '';
				this.areaId = '';
				this.cityId = '';
				//省级选择框
				getAreaListByLevel(null, 0).then(res => {
					this.areas = res.data.data;
				})
				this.onLoad(this.page);
			},
			//搜索
			searchChange(params,done) {
				this.page.currentPage=1;
				if(this.areaId){
					params.parentId = this.areaId;
				}
				if(this.cityId){
					params.parentId = this.cityId;
				}
				if(!this.areaId && !this.cityId){
					params = {};
				}
				this.idList = []
				this.$refs.crud.toggleSelection();
				this.query = params;
				this.onLoad(this.page, params,done);
			},
			//更改当前页数
			currentChange(currentPage) {
				this.page.currentPage = currentPage;
			},
			//更改一页多少条数据
			sizeChange(pageSize) {
				this.page.pageSize = pageSize;
			},
			refreshChange() {
				this.idList = []
				this.$refs.crud.toggleSelection();
				this.onLoad(this.page);
			},
			onLoad(page, params = {},done) {
				this.loading = true;
				getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
					if(done){
						done();
					}
					this.loading = false;
					const data = res.data;
					this.page.total = data.count;
					this.data = data.data;
				});
				//获取树里面的数据,并且过滤
                getListTree().then(res => {
                    var listTree = res.data.data;
                    for(let i=0;i<listTree.length;i++){
                        let item = listTree[i].children;
                        for(let y =0;y<item.length;y++){
                            item[y].children = [];
						}
					}
                    this.option.column[3].dicData = listTree;
                });
			},
			rowSwitchChange(row) {
				if (row.id) {
					if (row.common) {
						updateDisplay(row.id, "true");
					} else {
						updateDisplay(row.id, "false");
					}
				}
			},
			selectionChange(row) {
				var idList = []
				if (row.length > 0) {
					for (let item of row) {
						idList.push(item.id)
					}
					this.idList = idList
				}
				else {
					this.idList =[];
				}
			},
			//批量删除 
			deletAll() {
				removeAll(this.idList).then((res) => {
					this.page.currentPage = 1;
					if (res.data.code == 200) {
						this.onLoad(this.page);
						this.$message({
							type: "success",
							message: "操作成功!"
						});
					} else {
						this.$message.error(res.data.message);
					}
				});
			},
		}
	};
</script>

<style>
</style>
